package com.sp.shoppingplatform.service.impl;

import com.sp.shoppingplatform.entity.Product;
import com.sp.shoppingplatform.mapper.ProductMapper;
import com.sp.shoppingplatform.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    @Transactional
    public Product createProduct(Product product) {
        productMapper.insert(product);
        return product;
    }

    @Override
    @Cacheable(value = "product", key = "#id")
    public Product getProductById(Long id) {
        return productMapper.selectById(id);
    }

    @Override
    @Transactional
    @CacheEvict(value = "product", key = "#product.id")
    public boolean updateProduct(Product product) {
        return productMapper.update(product) > 0;
    }

    @Override
    @Transactional
    @CacheEvict(value = "product", key = "#id")
    public boolean deleteProduct(Long id) {
        return productMapper.deleteById(id) > 0;
    }

    @Override
    public List<Product> getProductList() {
        return productMapper.selectList();
    }

    @Override
    public List<Product> getProductsByCategory(String category) {
        return productMapper.selectByCategory(category);
    }
}
